package com.vimi8.ebb.api.ebb;

import com.vimi8.ebb.configuration.HttpResponseEntity;
import com.vimi8.ebb.configuration.OAuth2AuthenticationImpl;
import com.vimi8.ebb.model.ApplyRecord;
import com.vimi8.ebb.model.Error;
import com.vimi8.ebb.model.GeoCodings;
import com.vimi8.ebb.model.Paginator;
import com.vimi8.ebb.service.ApplyRecordService;
import com.vimi8.ebb.service.ElectricityBusinessService;
import com.vimi8.ebb.service.GeoCodingsService;
import com.vimi8.ebb.util.PagesUtil;
import com.vimi8.ebb.util.SubStringUtil;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * Created by think on 2017/6/12.
 */
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-09-19T10:01:46.405Z")

@Controller
public class ApplyRecordApiController implements ApplyRecordApi {


    private static final Logger logger = LoggerFactory.getLogger(ApplyRecordApiController.class);

    @Autowired
    private ApplyRecordService applyRecordService;
    @Autowired
    private ElectricityBusinessService electricityBusinessService;
    @Autowired
    private GeoCodingsService geoCodingsService;
    @Override
    public HttpResponseEntity<String> registerApplyRecord(@ApiParam(value = "申请信息.", required = true) @RequestBody ApplyRecord applyRecord) {
        try{
            int count =0;
            String id= UUID.randomUUID().toString();
            String userId = OAuth2AuthenticationImpl.openId();
            applyRecord.setId(id);
            applyRecord.setUserId(userId);
            int num=applyRecordService.getApplyRecordCount(applyRecord.getEbbId(),applyRecord.getUserId());
            if(num>0){
                return new HttpResponseEntity(new Error().error("error!").errorDescription("existed"),HttpStatus.SERVICE_UNAVAILABLE);
            }
            count=applyRecordService.insertApplyRecord(applyRecord);
            return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("error!").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @Override
    public HttpResponseEntity<Paginator<List<ApplyRecord>>> getApplyRecordList(
            @ApiParam(value = "页码", required = true) @RequestParam(value = "start", required = true) int start,
            @ApiParam(value = "数据大小", required = true) @RequestParam(value = "size", required = true) int size,
            @ApiParam(value = "审核状态", required = false) @RequestParam(value = "status", required = false) String status,
            @ApiParam(value = "电商名称", required = false) @RequestParam(value = "storeName", required = false) String storeName
    ) {

        try{
            String addressCode=null;
            String code=null;
            String orgClass = OAuth2AuthenticationImpl.ClientOrgClass();
            String userId=null;
           // String clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());
            if ("org_ebb_county".equals(orgClass)) {
                userId=OAuth2AuthenticationImpl.openId();
            }
            PagesUtil pagesUtil=new PagesUtil();
            pagesUtil.setPageSize(size);
            pagesUtil.setCurrentPage(start);
            if(start<1){
                pagesUtil.setCurrentPage(1);
            }
            logger.info("addressCode="+code);
            int count = applyRecordService.queryApplyRecordCount(storeName,status,userId);
            pagesUtil.setTotalCount(count);
            List<ApplyRecord> applyRecordList = applyRecordService.queryTradeDetailById(storeName,status,userId,
                    pagesUtil.getStartPage(),size);

            for (ApplyRecord applyRecord:applyRecordList){
                String address = electricityBusinessService.getClientAddressCode(applyRecord.getUserId());
                logger.info("addressCode:"+address);
                //解析地址
                if(!StringUtils.isEmpty(address)&&address.length()==12){
                    GeoCodings geoCodingsById = geoCodingsService.getGeoCodingsById(address);
                    applyRecord.setAddressCode(geoCodingsById==null?"":geoCodingsById.getGeoName());
                }
            }

            Paginator<List<ApplyRecord>> paginator = new Paginator<List<ApplyRecord>>(pagesUtil.getCurrentPage(),pagesUtil.getPageSize(),
                    pagesUtil.getTotalPage(),pagesUtil.getTotalCount(),applyRecordList);
            logger.info("applyRecordList:"+applyRecordList);

            return new HttpResponseEntity<Paginator<List<ApplyRecord>>>(paginator,HttpStatus.OK);

        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("error!").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @Override
    public HttpResponseEntity<String> updateApplyRecord(@ApiParam(value = "修改审核状态", required = true) @RequestBody ApplyRecord applyRecord) {

        int count = 0;
        try {
            if("1".equals(applyRecord.getApprovalStatus())){
                String addressCode = electricityBusinessService.getClientAddressCode(applyRecord.getUserId());
                count = electricityBusinessService.updateAddressCodeById(addressCode, applyRecord.getEbbId());
                count += applyRecordService.updateApplyStatus(applyRecord);
            }else{
                count = applyRecordService.updateApplyStatus(applyRecord);
            }


        }catch (Exception e){
        return new HttpResponseEntity(new Error().error("error!").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
    }


        return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<String> deleteApplyRecord(@ApiParam(value = "id", required = true) @RequestParam(value = "id", required = true) String id) {

        int count = 0;
        try {

            count = applyRecordService.deleteeApplyStatus(id);

        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("error!").errorDescription(e.getMessage()), HttpStatus.SERVICE_UNAVAILABLE);
        }
        return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
    }
}
